<template>
  <div>
    <el-form :model="formData" :rules="formRules" inline ref="formData" label-position="top" class="row-form">
      <el-card class="box-card">
        <div class="card-view">

          <div class="card-title">基础信息</div>

          <el-form-item label="园区名称" prop="gardenName" class="form-item-css">
            <el-input v-model="formData.gardenName" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="园区类型" prop="gardenType" class="form-item-css">
            <el-select v-model="formData.gardenType" placeholder="请选择" style="width: 100%">
              <el-option label="园区" :value="1"/>
              <el-option label="写字楼" :value="2"/>
            </el-select>
          </el-form-item>

          <el-form-item label="园区介绍" prop="text" class="form-item-css">
            <el-input v-model="formData.text" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="园区联系人姓名" prop="gardenContacts" class="form-item-css">
            <el-input v-model="formData.gardenContacts" placeholder="请输入" :maxlength="5"/>
          </el-form-item>

          <el-form-item label="园区联系方式" prop="gardenPhone" class="form-item-css">
            <el-input v-model="formData.gardenPhone" placeholder="请输入" :maxlength="11"/>
          </el-form-item>

          <el-form-item label="地址" prop="addressId" class="form-item-css">
            <el-cascader v-model="formData.addressId" ref="cascader" :props="props" @change="cascaderChange"
                         style="width: 100%" :key="formData.id"/>
          </el-form-item>

          <el-form-item label="详细地址" prop="address" class="form-item-css">
            <el-input v-model="formData.address" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="办公面积" prop="floorage" class="form-item-css">
            <el-input type="number" v-model="formData.floorage" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="竣工时间" prop="builtTime" class="form-item-css">
            <el-date-picker v-model="formData.builtTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"
                            style="width: 100%"/>
          </el-form-item>

          <el-form-item label="停车位" prop="parkingSpace" class="form-item-css">
            <el-input type="number" v-model="formData.parkingSpace" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="产权年限" prop="years" class="form-item-css">
            <el-input type="number" v-model="formData.years" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="园区标签" prop="gardenLabel" class="form-item-css">
            <el-input v-model="formData.gardenLabel" placeholder="请输入  多标签请用 ; 隔开" :maxlength="7"/>
          </el-form-item>

          <div class="form-item-css"></div>

          <el-form-item label="封面图片" prop="indexImage" class="form-item-css" v-if="!audit">
            <div class="image-view" v-if="formData.indexImage">
              <el-image :src="formData.indexImage" fit="cover" style="width: 100%; height: 100%"></el-image>
              <i class="el-icon-circle-close" @click="formData.indexImage = null"></i>
            </div>
            <UploadFile v-model="formData.indexImage" v-else style="width: 100%"/>
          </el-form-item>

          <el-form-item label="视频路径" prop="videoUrl" class="form-item-css">
            <div class="image-view" v-if="formData.videoUrl">
              <!--<el-image :src="formData.videoUrl" fit="cover" style="width: 100%"></el-image>-->
              <video :src="formData.videoUrl" controls="controls" style="width: 100%; height: 100%"></video>
              <i class="el-icon-circle-close" @click="formData.videoUrl = null" v-if="!audit"></i>
            </div>
            <UploadFile v-model="formData.videoUrl" fileType=".mp4,.mov" v-else style="width: 100%" v-if="!audit"/>
          </el-form-item>
          <div class="form-item-css"></div>
          <el-form-item label="内容图片" prop="" style="width: 100%;">
            <div class="row-start">
              <div class="image-list" v-for="(item, index) in formData.contentPicture">
                <el-image :src="item" fit="cover" class="image-item"></el-image>
                <div class="row-div image-hover" v-if="!audit">
                  <i class="el-icon-delete" @click="imageListDelete(index)"></i>
                </div>
              </div>
              <UploadFile multiple :file-list="formData.contentPicture" listType @change="fileListChange" v-if="!audit"/>
            </div>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="box-card">
        <div class="card-view">
          <div class="row-between  card-title">
            <div>配套信息</div>
            <el-button type="text" @click="formData.gardenServerId.push({ id: null })" v-if="!audit">新 增</el-button>
          </div>
          <el-form-item :label="`配套${index + 1}`" :prop="`gardenServerId.${index}.id`" class="form-item-css"
                        v-for="(items, index) in formData.gardenServerId" :key="index"
                        :rules="[{ required: true, message: '请选择配套', trigger: 'change' }]">
            <el-button type="text" class="delete-but" @click="assortInfoDelete(index)" v-if="!audit">删 除</el-button>
            <el-select v-model="items.id" filterable placeholder="请选择" style="width: 100%;">
              <el-option v-for="(item, index) in gardenServerList" :key="index" :label="item.name" :value="item.id"
                         :disabled="formData.gardenServerId.some(it => item.id == it.id)">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right;">
                   <el-image :src="item.image" fit="cover" style="width: 32px; height: 32px;"></el-image>
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="box-card">
        <div class="card-view">
          <div class="card-title">补充信息</div>
          <el-form-item label="物业公司名称" prop="manageCompany" class="form-item-css">
            <el-input v-model="formData.manageCompany" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="物业联系人" prop="manageName" class="form-item-css">
            <el-input v-model="formData.manageName" placeholder="请输入" :maxlength="5"/>
          </el-form-item>
          <el-form-item label="物业联系方式" prop="phone" class="form-item-css">
            <el-input type="number" v-model="formData.phone" placeholder="请输入" :maxlength="11"/>
          </el-form-item>
          <el-form-item label="物业费用" prop="propertyFee" class="form-item-css">
            <el-input type="number" v-model="formData.propertyFee" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="开发商" prop="developers" class="form-item-css">
            <el-input v-model="formData.developers" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="电梯" prop="elevator" class="form-item-css">
            <el-input v-model="formData.elevator" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="空调" prop="airConditioner" class="form-item-css">
            <el-input v-model="formData.airConditioner" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="标准层建面" prop="standardFloor" class="form-item-css">
            <el-input type="number" v-model="formData.standardFloor" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="容积率" prop="plotRatio" class="form-item-css">
            <el-input type="number" v-model="formData.plotRatio" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="网络通信" prop="network" class="form-item-css">
            <el-input v-model="formData.network" placeholder="请输入"/>
          </el-form-item>
        </div>
      </el-card>


      <el-card class="box-card">
        <div class="card-view">
          <div class="row-between card-title">
            <div>关联主账号</div>
            <el-button type="text" v-if="!audit" @click="formData.userRoleList.push({ wxUserId: null, roleType: 2 })">新 增</el-button>
          </div>
          <!--:rules="[{ required: true, message: '请选择账号UID', trigger: 'change' }]"-->
          <el-form-item :label="items.roleType == 1 ? '主账号UID' : '账号UID'" :prop="`userRoleList[${index}].wxUserId`"
                        v-for="(items,index) in formData.userRoleList" :key="index" class="form-item-css"
                        >
            <div v-if="items.roleType == 1 && !(!detailId)">
              <el-button type="warning" class="delete-but" style="color: white" v-if="alterUserId && !audit"
                         @click="alterUserId = false">更 换
              </el-button>
              <div v-else-if="!alterUserId">
                <el-button class="delete-but" style="color: #333;" @click="alterUserId = true">
                  取 消
                </el-button>
              </div>
            </div>
            <div v-else-if="items.roleType != 1">
              <el-button type="text" class="delete-but" @click="userRoleDelete(items,index)">删 除</el-button>
            </div>
            <el-select v-model="items.wxUserId" filterable placeholder="请选择"
                       @change="onEditUserIdEvent($event, items)" style="width: 100%;"
                       :disabled="items.roleType == 1 ? !(!detailId) && alterUserId : !(!items.id)">
              <el-option v-for="(item, index) in userList" :key="index" :label="item.nickName" :value="item.id"
                         :disabled="formData.userRoleList.some(it => item.id == it.wxUserId)">
                <span style="float: left">{{ item.nickName }}</span>
                <span style="float: right;">
                   <el-image :src="item.headimgUrl" fit="cover" style="width: 32px; height: 32px;"></el-image>
                </span>
              </el-option>
            </el-select>

          </el-form-item>
        </div>
      </el-card>

      <div class="row-div" style="margin: 30px 0" v-if="audit">
        <el-button style="width: 300px" @click="$router.go(-1)">取 消</el-button>
        <el-button type="warning" style="width: 300px"  @click="auditGarden(2)">驳 回</el-button>
        <el-button type="primary" style="width: 300px"  @click="auditGarden(0)">通 过</el-button>
      </div>
      <div class="row-div" style="margin: 30px 0" v-else>
        <el-button style="width: 300px" @click="$router.go(-1)">取 消</el-button>
        <el-button type="primary" style="width: 300px"  @click="detailId ? onEditEvent() : onSubmit()">提 交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import {getProvinces} from '@/utils/common.js'
  export default {
    computed: {
      ...mapGetters(['confirm'])
    },
    name: 'parkAdd',
    data() {
      return {
        alterUserId: true,
        detailId: null, // 详情ID
        gardenServerList: [], // 园区服务列表
        userList: [], // 用户列表
        formData: {
          id: null,
          gardenName: null, // 园区名字
          gardenContacts: null, // 园区联系人
          gardenPhone: null, // 园区联系电话
          gardenServerId: [{ id: null }], // 园区服务：json数组
          contentPicture: [], // 内容图片
          gardenLabel: null, // 园区标签
          gardenType: null, // 园区类型：1园区；2写字楼
          indexImage: null, // 封面图片
          addressId: null, // 省市区
          province: null, // 省
          city: null, // 市
          county: null, // 区
          address: null, // 详细地址
          ambitus: null, // 位置周边
          videoUrl: null, // 视频路径
          years: null, // 产权年限
          airConditioner: null, // 空调
          browseCount: null, // 浏览次数
          builtTime: null, // 建成时间
          checkReason: null, // 审核拒绝原因
          checkStatus: null, // 审核状态：0正常（通过）；1待审核； 2拒绝
          companyId: null, // 物业管理公司id
          createTime: null, // 创建时间
          decoration: null, // 装修情况
          developers: null, // 开发商
          elevator: null, // 电梯
          floorTall: null, // 标准层高
          floorage: null, // 建筑面积
          manageCard: null, // 管理员身份证号
          manageCompany: null, // 管理公司名称
          manageName: null, // 管理员姓名
          network: null, // 网络通信
          onlineRent: null, // 在租套数
          parkingSpace: null, // 停车位
          phone: null, // 物业手机号码
          plotRatio: null, // 容积率
          propertyFee: null, // 物业费
          standardFloor: null, // 标准层建面
          text: null, // 园区介绍
          totalHousing: null, // 房屋总套数
          userRoleList: [{ wxUserId: null, roleType: 1 }] // 角色用户列表
        },
        formRules: {
          wxUserId: [
            { required: true, message: '请选择主账号UID', trigger: 'change' }
          ], // 用户id
          gardenName: [
            { required: true, message: '请输入园区名称', trigger: 'blur' }
          ], // 园区名字
          gardenContacts: [
            { required: true, message: '请输入园区联系人', trigger: 'blur' }
          ], // 园区联系人
          gardenPhone: [
            { required: true, message: '请输入园区联系电话', trigger: 'blur' }
          ], // 园区联系电话
          gardenLabel: [
            { required: true, message: '请输入园区标签', trigger: 'blur' }
          ], // 园区标签
          gardenType: [
            { required: true, message: '请选择园区类型', trigger: 'change' }
          ], // 园区类型：1园区；2写字楼
          indexImage: [
            { required: true, message: '请上传封面图片', trigger: 'change' }
          ], // 封面图片
          addressId: [
            { required: true, message: '请选择省市区', trigger: 'change' }
          ], // 省市区
          years: [
            { required: true, message: '请输入产权年限', trigger: 'change' }
          ], // 产权年限
          address: [
            { required: true, message: '请输入详情地址', trigger: 'blur' }
          ], // 详细地址
          airConditioner: [
            { required: true, message: '请输入空调信息', trigger: 'blur' }
          ], // 空调
          browseCount: [
            { required: true, message: '请输入浏览次数', trigger: 'blur' }
          ], // 浏览次数
          builtTime: [
            { required: true, message: '请选择建成时间', trigger: 'blur' }
          ], // 建成时间
          decoration: [
            { required: true, message: '请输入装修情况', trigger: 'blur' }
          ], // 装修情况
          developers: [
            { required: true, message: '请输入开发商', trigger: 'blur' }
          ], // 开发商
          elevator: [
            { required: true, message: '请输入电梯信息', trigger: 'blur' }
          ], // 电梯
          floorTall: [
            { required: true, message: '请输入标准层高', trigger: 'blur' }
          ], // 标准层高
          floorage: [
            { required: true, message: '请输入建筑面积', trigger: 'blur' }
          ], // 建筑面积
          manageCompany: [
            { required: true, message: '请输入管理公司名称', trigger: 'blur' }
          ], // 管理公司名称
          manageName: [
            { required: true, message: '请输入管理员姓名', trigger: 'blur' }
          ], // 管理员姓名
          network: [
            { required: true, message: '请输入网络通信', trigger: 'blur' }
          ], // 网络通信
          onlineRent: [
            { required: true, message: '请输入在租套数', trigger: 'blur' }
          ], // 在租套数
          parkingSpace: [
            { required: true, message: '请输入停车位', trigger: 'blur' }
          ], // 停车位
          phone: [
            { required: true, message: '请输入物业手机号码', trigger: 'blur' }
          ], // 物业手机号码
          plotRatio: [
            { required: true, message: '请输入容积率', trigger: 'blur' }
          ], // 容积率
          propertyFee: [
            { required: true, message: '请输入物业费', trigger: 'blur' }
          ], // 物业费
          standardFloor: [
            { required: true, message: '请输入标准层建面', trigger: 'blur' }
          ], // 标准层建面
          text: [
            { required: true, message: '请输入园区介绍', trigger: 'blur' }
          ], // 园区介绍
          // videoUrl: [
          //   { required: true, message: '请上传视频', trigger: 'blur' }
          // ] // 视频路径
        },
        props: getProvinces(),
        audit: 0
      }
    },
    async beforeMount() {
      this.detailId = this.$route.query.id || null
      this.audit = this.$route.query.audit || 0
      await this.getUserList()
      if (this.detailId) {
        await this.getGardenInfo()
      }
      await this.getGardenServerList()
    },
    methods: {
      auditGarden (type) {
        if (type == 0) {
          this.$confirm('此操作将无法修改是否继续', '提示', this.confirm.options).then(async() => {
            await this.$ajax.post(`/garden/update`, {
              id: this.detailId,
              checkStatus: 0,
              shelfStatus: 1
            })
            this.$message.success('操作成功')
            this.$router.go(-1)
          })
        } else if (type == 2) {
          this.$prompt('请输入拒绝理由', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(async ({ value }) => {
            if (!value) return this.$message.warning('请输入拒绝理由')
            await this.$ajax.post(`/garden/update`, {
              id: this.detailId,
              checkStatus: 2,
              checkReason: value
            })
            this.$message.success('操作成功')
            this.$router.go(-1)
          })
        }
      },
      /**
       * 修改园区
       */
      onEditEvent() {
        this.$refs.formData.validate(async(valid) => {
          if (!valid) return this.$message.warning('请完善信息')
          const formData = JSON.parse(JSON.stringify(this.formData))
          formData.gardenServerId = formData.gardenServerId.map(item => item.id).join(',')
          formData.contentPicture = formData.contentPicture.join(',')
          formData.addressId = formData.addressId.join(',')
          await this.$ajax.post('/garden/backstage/update', formData)
          this.$message.success('修改成功!')
          this.$router.push('/parkManage/parkList')
        })
      },
      /**
       * 新增园区
       */
      onSubmit() {
        this.$refs.formData.validate(async(valid) => {
          if (!valid) return this.$message.warning('请完善信息')
          const formData = JSON.parse(JSON.stringify(this.formData))
          const reg = /^\d{11}$/
          formData.gardenServerId = formData.gardenServerId.map(item => item.id).join(',')
          formData.contentPicture = formData.contentPicture.join(',')
          formData.addressId = formData.addressId.join(',')
          if (formData.gardenLabel.split(';').length > 2) return this.$message.warning("标签内容较多")
          if (!reg.test(formData.gardenPhone)) return this.$message.warning("请输入正确的手机号码")
          const res = await this.$ajax.post('/garden/backstage/add', formData)
          const list = formData.userRoleList;
          for(let i = 0; i < list.length; i++){
            const item = list[i]
            await this.$ajax.post('/wx/role/add', { roleType: item.roleType, gardenId: res.data.id, wxUserId: item.wxUserId })
          }
          this.$message.success('新增成功!')
          this.formData.contentPicture = []
          this.$refs.formData.resetFields()
          this.$router.push('/parkManage/parkList')
        })
      },
      /**
       * 获取园区详情
       */
      async getGardenInfo() {
        const res = await this.$ajax.get(`/garden/backstage/info?id=${this.detailId}`)
        const gardenServerId = res.data.gardenServerId ? res.data.gardenServerId.split(',') : []
        res.data.gardenServerId = gardenServerId.length <= 0 ? [{ id: null }] : gardenServerId.map((item) => ({ id: item }))
        res.data.contentPicture = res.data.contentPicture ? res.data.contentPicture.split(',') : []
        res.data.latitude = parseInt(res.data.latitude) || null
        res.data.longitude = parseInt(res.data.longitude) || null
        res.data.addressId = res.data.addressId ? res.data.addressId.split(',') : null
        res.data.userRoleList = [{ wxUserId: null, roleType: 1 }]
        delete res.data.userId
        this.formData = res.data
        await this.getUidRoleList()
      },
      /**
       * 删除账号UID
       */
      userRoleDelete (item, index) {
        if (!item.id) {
          if (this.formData.userRoleList.length <= 1) return this.$message.warning("主账号不能删除")
          return this.formData.userRoleList.splice(index, 1)
        }
        this.$confirm(this.confirm.text, '提示', this.confirm.options).then(async() => {
          await this.$ajax.get(`/wx/role/remove?id=${item.id}`)
          this.$message.success('操作成功')
          this.formData.userRoleList.splice(index, 1)
        })
      },
      /**
       * 修改主账号UID
       */
      async onEditUserIdEvent(event, user) {
        if (!this.detailId) return;
        await this.$ajax.post(user.id ? '/garden/backstage/role' : '/wx/role/add', {
          roleType: user.roleType,
          gardenId: this.detailId,
          id: user.id || null,
          wxUserId: user.wxUserId,
        })
        this.alterUserId = true
        this.$message.success('操作成功')
        this.getGardenInfo()
      },
      /**
       * 获取主账号Uid列表
       */
      async getUidRoleList() {
        const res = await this.$ajax.get(`/wx/role/list?gardenId=${this.detailId}`)
        this.formData.userRoleList = res.rows && res.rows.length ? res.rows : [{ wxUserId: null, roleType: 1 }]
      },
      /**
       * 获取园区服务列表
       */
      async getUserList() {
        const res = await this.$ajax.get('/wx/user/phone/search')
        this.userList = res.rows
      },
      /**
       * 获取园区服务列表
       */
      async getGardenServerList() {
        const res = await this.$ajax.get('/garden/server/list')
        this.gardenServerList = res.rows
      },
      /**
       * 图片列表删除事件
       */
      imageListDelete(index) {
        this.formData.contentPicture.splice(index, 1)
      },
      /**
       * 内容图片变化事件
       */
      fileListChange(event) {
        this.formData.contentPicture = event
      },
      /**
       * 配套信息删除事件
       */
      assortInfoDelete(index) {
        this.formData.gardenServerId.length <= 1 ? this.$message.warning('配套信息最少选择一套') : this.formData.gardenServerId.splice(index, 1)
      },
      /**
       * 省市区变化事件
       */
      cascaderChange(event) {
        const entity = this.$refs.cascader.getCheckedNodes()[0]
        const list = entity && entity.pathLabels && entity.pathLabels.length > 0 ? entity.pathLabels : [null, null, null]
        let arr = ['province', 'city', 'county']
        for (let i = 0; i < list.length; i++) this.formData[arr[i]] = list[i]
      }
    }
  }
</script>

<style scoped lang="scss">
  .box-card + .box-card {
    margin-top: 20px;
  }

  .image-list {
    width: 148px;
    height: 148px;
    position: relative;
    margin-right: 10px;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    &:hover > .image-hover {
      display: flex;
      z-index: 1;
    }
    .image-item, .image-hover {
      width: 100%;
      height: 100%;
      border-radius: 6px;
    }
    .image-hover {
      position: absolute;
      top: 0;
      left: 0;
      display: none;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      font-size: 20px;
    }
  }

  .card-view {
    width: 100%;
    .card-title {
      width: 200px;
      font-weight: bold;
      font-size: 18px;
      padding-bottom: 10px;
      margin-bottom: 20px;
      position: relative;
      &:before {
        content: "";
        width: 200px;
        height: 1px;
        background: #000000;
        position: absolute;
        bottom: 0;
        left: 0;
      }
    }

    .form-item-css {
      width: calc(100% / 3 - 10px);
      position: relative;
      .delete-but {
        position: absolute;
        color: red;
        z-index: 2;
        right: 0;
        top: -40px;
      }
    }
  }

  .image-view {
    width: 100%;
    height: 178px;
    position: relative;
    .el-icon-circle-close {
      font-size: 30px;
      color: red;
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 100;
    }
    .el-icon-circle-close:hover {
      cursor: pointer;
    }
  }
</style>
